import * as api from '@/services/vpnServerCheck';
import * as apiChecker from '@/services/vpnServerChecker';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable, { EditableProTable } from '@ant-design/pro-table';
import { Badge, Button, Card, Checkbox, Col, Popconfirm, Row, Tabs, Tag, TreeSelect } from 'antd';
import TabPane from 'antd/lib/tabs/TabPane';
import React, { useEffect, useRef, useState } from 'react';
import * as c from '@/services/consts';
import { useModel } from 'umi';

type VpnServerFormProps = {
  visible: boolean;
  groupIds: string[];
  instIds: number[];
  // groups: API.VpnGroupMonitorModel[] ;
  servers: API.VpnServerMonitorModel[];
  serverType: number;
  onCancel: () => void;
  onSubmit: () => Promise<void>;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, groupIds, instIds, servers, serverType, onCancel, onSubmit } =
    props;

  if (!visible) {
    return null;
  }

  // console.log(groupIds, groups, instIds, servers);

  const [myloading, setMyloading] = useState<boolean>(true);
  const [dataSource, setDataSource] = useState<API.VpnServerCheck | undefined>(
    undefined,
  );
  const [dataCheckers, setDataCheckers] = useState<
    API.VpnServerChecker[] | undefined
  >(undefined);
  const [checkedList, setCheckedList] = useState<any[]>([]);
  const [uncheckeBlock, setUncheckeBlock] = useState<boolean>(false);
  // const [groupEditableKeys, setGroupEditableKeys] = useState<React.Key[]>(() =>
  //   groupIds.map((item) => item),
  // );
  const [serverEditableKeys, setServerEditableKeys] = useState<React.Key[]>(
    () => instIds.map((item) => item),
  );
  const [selGroupIds, setSelGroupIds] = useState<string[] | undefined>(groupIds);

  const formRef = useRef<ProFormInstance>();
  // const editorFormRef = useRef<EditableFormInstance<API.VpnServerNet>>();
  
  const { getVpnGroupExTrees, supplierOptions } = useModel('useGlobalModel', (model) => ({
    getVpnGroupExTrees: model.getVpnGroupExTrees,
    supplierOptions: model.supplierOptions,
  }));

  const loadData = async () => {
    const result = await api.get();
    if (result && result.success) {
      console.log(result);
      setDataSource(result.data);
    }

    const resultChecker = await apiChecker.list();
    if (resultChecker && resultChecker.data) {
      // let options : any[] = [];
      // resultChecker.data.forEach(el => {
      //   if(el.status){
      //     options.push(el.id);
      //   }
      // });
      // setCheckedList(options);
      setDataCheckers(resultChecker.data);
    } else {
      setDataCheckers([]);
    }

    setMyloading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleSubmit = async (updateVer: boolean) => {
    // if(checkedList && checkedList.length == 0){
    //   message.error("请选择用于检测的服务器");
    //   return;
    // }
    // console.log(groupEditableKeys, serverEditableKeys);
    let data = {
      groupIds: selGroupIds,// groupEditableKeys.map((val) => val.toString()),
      instIds: serverEditableKeys.map((val) => val as number),
      checkers: checkedList,
      updateVer: updateVer,
      uncheckBlock: uncheckeBlock,
      serverType: serverType
    };
    const result = await api.update(data);
    if (result && result.success) {
      onSubmit();
    }
  };

  // const newGroupColumns: ProColumns<API.VpnGroupMonitorModel>[] = [
  //   // {
  //   //   title: 'ID',
  //   //   dataIndex: 'id',
  //   //   width:100,
  //   // },
  //   {
  //     title: '名称',
  //     dataIndex: 'name',
  //     readonly: true,
  //   },
  //   {
  //     title: '操作',
  //     valueType: 'option',
  //     width: 60,
  //   },
  // ];

  const newServerColumns: ProColumns<API.VpnServerMonitorModel>[] = [
    {
      title: '实例ID',
      dataIndex: 'instanceId',
      readonly: true,
      width: 200,
    },
    {
      title: '名称',
      dataIndex: 'name',
      readonly: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 60,
    },
  ];

  const groupColumns: ProColumns<API.VpnGroupModel>[] = [
    // {
    //   title: 'ID',
    //   dataIndex: 'id',
    //   width: 200,
    // },
    {
      title: '名称',
      dataIndex: 'name',
    },
  ];

  const serverColumns: ProColumns<API.VpnServer>[] = [
    {
      title: '实例ID',
      dataIndex: 'instanceId',
      width: 200,
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
  ];

  return (
    <DrawerForm<API.VpnServerCheckModel>
      open={visible}
      title={
        <>
          检测配置 <Tag color="orange">{dataSource?.serverType == 2 ? 'XVPN' : "VPN"}</Tag><Tag color="blue">版本：{dataSource?.ver}</Tag>{' '}
          <Tag color="blue">下发时间：{`${dataSource?.createTime}`}</Tag>{' '}
          <Tag color="blue">创建人：{dataSource?.createUser}</Tag>{' '}
        </>
      }
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      // onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [defaultDoms[0]];
        },
      }}
    >
      <Card loading={myloading}>
        <Tabs
          type="card"
          tabBarExtraContent={
            <>
              {/* <Popconfirm
                key="update_confirm"
                title="确定要更新检测配置吗?"
                onConfirm={async () => {
                  await handleSubmit(true);
                }}
              >
                <Button type="primary" style={{ marginRight: 10 }}>
                  加入当前检测
                </Button>
              </Popconfirm>

              <Popconfirm
                key="replace_confirm"
                title="确定要新建检测配置吗?"
                onConfirm={async () => {
                  await handleSubmit(false);
                }}
              >
                <Button type="primary" danger>
                  新建检测
                </Button>
              </Popconfirm> */}
              <Popconfirm
                key="replace_confirm"
                title="确定要下发检测配置吗?"
                onConfirm={async () => {
                  await handleSubmit(false);
                }}
              >
                <Button type="primary" danger>
                下发检测
                </Button>
              </Popconfirm>
            </>
          }
        >
          <TabPane
            tab="新增检测配置"
            key="1"
            style={{
              border: 1,
              borderStyle: 'solid',
              borderColor: '#eee',
              marginTop: -18,
              minHeight: 410,
            }}
          >
            <Card
              title={
                <>
                  指定检测的服务器 <Tag color="blue">不选表示全部</Tag>
                </>
              }
              headStyle={{ backgroundColor: '#fafafa' }}
            >
              <Checkbox.Group key="ckgPlat" onChange={setCheckedList}>
                {dataCheckers?.map((gc) => {
                  let text = `${gc.name} [${gc.ip}]`;
                  return (
                    <Checkbox value={gc.id} style={{ verticalAlign: 'middle' }}>
                      {gc.status ? (
                        <Badge color="#52c41a" text={text} />
                      ) : (
                        <Badge color="#f50" text={text} />
                      )}
                    </Checkbox>
                  );
                })}
              </Checkbox.Group>
            </Card>

            <Card
              title={
                <>
                  检测的分组和服务器　
                  <Checkbox
                    checked={uncheckeBlock}
                    onChange={(e) => {
                      setUncheckeBlock(e.target.checked);
                    }}
                    style={{ color: 'blue', fontWeight: 'bold' }}
                  >
                    不检测被墙
                  </Checkbox>
                </>
              }
              headStyle={{ backgroundColor: '#fafafa' }}
            >
              {/* <EditableProTable<API.VpnGroupMonitorModel | API.NodeGroupMonitorModel>
                rowKey="id"
                // editableFormRef={editorFormRef}
                headerTitle="分组"
                locale={{ emptyText: '暂无数据' }}
                // toolBarRender={false}
                columns={newGroupColumns}
                defaultValue={groups}
                // onChange={setDataSource}
                recordCreatorProps={false}
                editable={{
                  type: 'multiple',
                  editableKeys: groupEditableKeys,
                  actionRender: (row, config, defaultDom) => [
                    defaultDom.delete,
                  ],
                  // onValuesChange: (record, recordList) => {
                  //   //setDataSource(recordList);
                  // },
                  onChange: setGroupEditableKeys,
                }}
                // request={async () => ({
                //   data: dataSource,
                //   success: true,
                // })}
                // params={{ d: dataSource }}
              /> */}

              
            <Row gutter={24}>
              <Col span={24}>分组
                <TreeSelect
                  style={{ minWidth: '100%', marginTop: 0, marginBottom: 30 }}
                  listHeight={600}
                  // maxTagCount={1}
                  // dropdownMatchSelectWidth={false}
                  placeholder="选择分组过滤"
                  allowClear={true}
                  showSearch={true}
                  treeCheckable={true}
                  // multiple={false}
                  treeDefaultExpandAll
                  treeData={getVpnGroupExTrees(undefined)}
                  value={selGroupIds}
                  treeNodeFilterProp="title"
                  onChange={(value) => {
                    setSelGroupIds(value ? value : undefined);
                  }}
                />
              </Col>
            </Row>

              <EditableProTable<API.VpnServerMonitorModel>
                rowKey="instanceId"
                headerTitle="服务器"
                locale={{ emptyText: '暂无数据' }}
                columns={newServerColumns}
                defaultValue={servers}
                recordCreatorProps={false}
                editable={{
                  type: 'multiple',
                  editableKeys: serverEditableKeys,
                  actionRender: (row, config, defaultDom) => [
                    defaultDom.delete,
                  ],
                  onChange: setServerEditableKeys,
                }}
              />
            </Card>
          </TabPane>
          <TabPane
            tab="当前配置"
            key="2"
            style={{
              border: 1,
              borderStyle: 'solid',
              borderColor: '#eee',
              marginTop: -18,
              minHeight: 410,
            }}
          >
            <Card
              title="指定检测的服务器"
              headStyle={{ backgroundColor: '#fafafa' }}
            >
              {
                dataSource?.checkers ? (
                  dataSource?.checkers.map((gc) => {
                    return (
                      <Tag color="blue">
                        {gc.name} [{gc.ip}]
                      </Tag>
                    );
                  })
                ) : (
                  <Tag color="blue">全部</Tag>
                )
                // dataCheckers?.map((gc)=>{
                //   return <Tag color='blue'>{gc.name} [{gc.ip}]</Tag>
                // })
              }
            </Card>
            <Card
              title={
                <>
                  检测的分组和服务器　
                  {dataSource?.checkConfig?.uncheckBlock == true ? (
                    <Tag color="blue">不检测被墙</Tag>
                  ) : (
                    ''
                  )}
                </>
              }
              headStyle={{ backgroundColor: '#fafafa' }}
            >
              <ProTable<API.VpnGroupModel>
                rowKey="id"
                headerTitle="分组"
                options={{
                  fullScreen: false,
                  reload: false,
                  setting: false,
                  density: false,
                }}
                search={false}
                pagination={false}
                columns={groupColumns}
                expandable={undefined}
                dataSource={dataSource?.groups}
              />
              <ProTable<API.VpnServer>
                rowKey="instanceId"
                headerTitle="服务器"
                options={{
                  fullScreen: false,
                  reload: false,
                  setting: false,
                  density: false,
                }}
                search={false}
                pagination={false}
                columns={serverColumns}
                dataSource={dataSource?.servers}
              />
            </Card>
          </TabPane>
        </Tabs>
      </Card>
    </DrawerForm>
  );
};

export default VpnServerForm;
